//
//  ZMWebViewVC.swift
//  IntelligentBoiler
//
//  Created by Rowling on 2020/5/17.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit
import WebKit

class ZMWebViewVC: ZMViewController, WKNavigationDelegate, UIScrollViewDelegate {

    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var titleLab: UILabel!
    @IBOutlet weak var timeLab: UILabel!
    @IBOutlet weak var webView: UIView!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var nextBtn: UIButton!
    
    var backgroundColorHexString : String?
    
    var bottomBtnClickBlock:(()->())?
    /// 加载完成回调
    var loadFinishBlock:(()->())?
    
    var url = ""
    var titleStr = ""
    var timeStr = ""
    var htmlStr = ""
    var barHidden = false
    var showBottom = true
    override func viewDidLoad() {
        super.viewDidLoad()
        if barHidden {
            setLeftBtn(imgStr: "")
            hbd_barHidden = true
        }
        if titleStr != "" {
            topView.isHidden = false
            titleLab.text = titleStr
            timeLab.text = timeStr
        }
        bottomView.isHidden = showBottom
        if htmlStr != "" {
            wkWeb.loadHTMLString(htmlStr, baseURL: nil)
        } else {
            if url.contains("support.qq.com") {
                self.title = "意见反馈"
                let request = NSMutableURLRequest(url: URL(string: url)!)
                request.httpMethod = "POST"
                request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                //            let body = String(format: "nickname=%@&avatar=%@&openid=%@", ZMAppShareData.share.user!.nickname, ZMAppShareData.share.user!.avatar, ZMAppShareData.share.user!.id).data(using: .utf8)
                //            request.httpBody = body
                wkWeb.load(request as URLRequest)
            } else if url.contains("http") {
                wkWeb.load(URLRequest(url: URL(string: url)!))
            } else {
                ZMToast.showToast(title: "不是正确的URL地址")
                navigationController?.popViewController(animated: true)
            }
        }
        view.addSubview(progress)
        view.bringSubviewToFront(progress)
        progress.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(2)
        }
    }
    
    @IBAction func nextClick(_ sender: UIButton) {
        if let block = bottomBtnClickBlock {
            block()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //  加载进度条
        if keyPath == "estimatedProgress"{
            progress.alpha = 1.0
            progress.setProgress(Float((self.wkWeb.estimatedProgress) ), animated: true)
            if (self.wkWeb.estimatedProgress )  >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progress.alpha = 0
                }, completion: { (finish) in
                    self.progress.setProgress(0.0, animated: false)
                })
            }
        }
    }
    
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
        if webView.title != "" {
            self.title = webView.title
        }
        DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 3) { [weak self] in
            guard let self = self else {return}
            if let block = self.loadFinishBlock {
                block()
            }
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let req = navigationAction.request;
        if let url = req.url, url.absoluteString.starts(with: "alipay://") {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        decisionHandler(.allow)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !topView.isHidden {
            topConstraint.constant = -scrollView.contentOffset.y
        }
    }
    
    lazy var progress: UIProgressView = {
        let progress = UIProgressView(progressViewStyle: .default)
        progress.progressTintColor = UIColor.zm.colorBase()
        progress.trackTintColor = .white
        return progress
    }()
    
    lazy var wkWeb: WKWebView = {
        let userContentController = WKUserContentController()
        var webWidth = ""
        if #available(iOS 11.0, *) {
            webWidth = "device-width";
        } else {
            webWidth = String(format: "%.f", UIScreen.main.scale * SCREEN_W)
        }
        var jSString = String(format: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%@'); document.getElementsByTagName('head')[0].appendChild(meta);", webWidth)
        if let backgroundColorHexString = backgroundColorHexString {
            jSString.append(contentsOf: "document.getElementsByTagName('body')[0].style.backgroundColor='\(backgroundColorHexString)';")
        }
        let wkUserScript = WKUserScript(source: jSString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        userContentController.addUserScript(wkUserScript)
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = userContentController
        wkWebConfig.allowsInlineMediaPlayback = true
        let web = WKWebView(frame: CGRect.zero, configuration: wkWebConfig)
        web.scrollView.showsVerticalScrollIndicator = false
        web.backgroundColor = .white
        web.navigationDelegate = self
        web.scrollView.delegate = self
        web.scrollView.bounces = false
        web.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webView.addSubview(web)
        web.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        return web
    }()
}
